from flask import render_template, redirect, url_for, flash, request, send_from_directory, current_app, jsonify, abort
from app.main import bp
from flask_login import login_required, current_user
from app.models import Thesis, Message
from app import db
from app.main.forms import ThesisForm
import os
from werkzeug.utils import secure_filename
from datetime import datetime

@bp.route('/')
@bp.route('/index')
def index():
    # 只有登录用户才重定向
    if current_user.is_authenticated:
        # 如果是管理员，重定向到管理后台
        if current_user.is_admin:
            return redirect(url_for('admin.index'))
        # 普通用户重定向到论文列表
        return redirect(url_for('main.my_theses'))
    # 未登录用户显示首页
    return render_template('index.html', title='首页')

@bp.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html', title='控制面板')

@bp.route('/submit_thesis', methods=['GET', 'POST'])
@login_required
def submit_thesis():
    form = ThesisForm()
    if form.validate_on_submit():
        # 计算基础价格
        base_price = {
            'design': 700,
            'thesis': 500,
            'full': 1000
        }.get(form.thesis_type.data, 0)  # 如果没有选择类型，默认为0
        
        # 计算总价
        total_price = base_price + form.price.data
        if form.need_environment.data:
            total_price += 100
            
        thesis = Thesis(
            title=form.title.data,
            description=form.description.data,
            programming_language=form.programming_language.data,
            thesis_type=form.thesis_type.data,
            price=total_price,
            user=current_user,
            contact_info=form.contact_info.data,
            deadline=form.deadline.data,
            need_environment=form.need_environment.data
        )
        
        # 如果上传了文件，则处理文件
        if form.proposal_file.data:
            f = form.proposal_file.data
            filename = secure_filename(f.filename)
            unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
            upload_dir = os.path.join(current_app.root_path, 'static', 'uploads')
            os.makedirs(upload_dir, exist_ok=True)
            file_path = os.path.join(upload_dir, unique_filename)
            f.save(file_path)
            thesis.proposal_file = unique_filename
        
        db.session.add(thesis)
        db.session.commit()
        flash('论文信息提交成功！')
        return redirect(url_for('main.my_theses'))
    return render_template('main/submit_thesis.html', title='提交论文', form=form, today=datetime.today())

@bp.route('/my_theses')
@login_required
def my_theses():
    page = request.args.get('page', 1, type=int)
    pagination = Thesis.query.filter_by(user_id=current_user.id)\
        .order_by(Thesis.created_at.desc())\
        .paginate(page=page, per_page=10, error_out=False)
    theses = pagination.items
    return render_template('main/thesis_list.html', 
                         title='我的论文', 
                         theses=theses,
                         pagination=pagination)

# 添加文件下载路由
@bp.route('/download_proposal/<filename>')
@login_required
def download_proposal(filename):
    return send_from_directory(
        os.path.join(current_app.root_path, 'static', 'uploads'),
        filename,
        as_attachment=True
    ) 

@bp.route('/edit_thesis/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_thesis(id):
    thesis = Thesis.query.get_or_404(id)
    if thesis.user_id != current_user.id:
        flash('您没有权限编辑这篇论文。')
        return redirect(url_for('main.my_theses'))
    
    form = ThesisForm(is_edit=True)
    if form.validate_on_submit():
        thesis.title = form.title.data
        thesis.description = form.description.data
        thesis.programming_language = form.programming_language.data
        thesis.price = form.price.data
        thesis.contact_info = form.contact_info.data
        thesis.deadline = form.deadline.data
        thesis.need_environment = form.need_environment.data
        
        # 如果上传了新文件
        if form.proposal_file.data:
            # 删除旧文件
            if thesis.proposal_file:
                old_file = os.path.join(current_app.root_path, 'static', 'uploads', thesis.proposal_file)
                if os.path.exists(old_file):
                    os.remove(old_file)
            
            # 保存新文件
            f = form.proposal_file.data
            filename = secure_filename(f.filename)
            unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
            upload_dir = os.path.join(current_app.root_path, 'static', 'uploads')
            os.makedirs(upload_dir, exist_ok=True)
            file_path = os.path.join(upload_dir, unique_filename)
            f.save(file_path)
            thesis.proposal_file = unique_filename
        
        db.session.commit()
        flash('论文信息已更新！')
        return redirect(url_for('main.thesis_detail', id=thesis.id))
    
    elif request.method == 'GET':
        form.title.data = thesis.title
        form.description.data = thesis.description
        form.programming_language.data = thesis.programming_language
        form.price.data = thesis.price
        form.contact_info.data = thesis.contact_info
        form.deadline.data = thesis.deadline
        form.need_environment.data = thesis.need_environment
    
    return render_template('main/edit_thesis.html', title='编辑论文', form=form, thesis=thesis, today=datetime.today())

@bp.route('/delete_thesis/<int:id>', methods=['POST'])
@login_required
def delete_thesis(id):
    thesis = Thesis.query.get_or_404(id)
    # 检查权限：只有论文作者可以删除
    if thesis.user_id != current_user.id:
        flash('您没有权限删除这篇论文。')
        return redirect(url_for('main.my_theses'))
    
    # 删除关联的文件
    if thesis.proposal_file:
        file_path = os.path.join(current_app.root_path, 'static', 'uploads', thesis.proposal_file)
        if os.path.exists(file_path):
            os.remove(file_path)
    
    db.session.delete(thesis)
    db.session.commit()
    flash('论文已删除！')
    return redirect(url_for('main.my_theses')) 

@bp.route('/thesis/<int:id>')
@login_required
def thesis_detail(id):
    thesis = Thesis.query.get_or_404(id)
    # 检查权限：只有论文作者和管理员可以查看详情
    if thesis.user_id != current_user.id and not current_user.is_admin:
        flash('您没有权限查看这篇论文。')
        return redirect(url_for('main.my_theses'))
    
    # 获取来源页面
    source = request.args.get('source', 'user')  # 默认来自用户页面
    return render_template('main/thesis_detail.html', 
                         title='论文详情', 
                         thesis=thesis,
                         source=source) 

@bp.route('/messages')
@login_required
def messages():
    page = request.args.get('page', 1, type=int)
    pagination = Message.query.filter_by(user_id=current_user.id)\
        .order_by(Message.created_at.desc())\
        .paginate(page=page, per_page=10, error_out=False)
    messages = pagination.items
    return render_template('main/messages.html', 
                         title='我的消息', 
                         messages=messages,
                         pagination=pagination)

@bp.route('/message/<int:id>/read', methods=['POST'])
@login_required
def mark_message_read(id):
    message = Message.query.get_or_404(id)
    if message.user_id != current_user.id:
        abort(403)
    message.is_read = True
    db.session.commit()
    return jsonify({'success': True}) 

@bp.route('/unread_count')
@login_required
def get_unread_count():
    unread_count = Message.query.filter_by(
        user_id=current_user.id,
        is_read=False
    ).count()
    return jsonify({'count': unread_count}) 

@bp.route('/process')
def process():
    return render_template('main/process.html', title='交付流程') 